<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考试中心 - 局域网视频学习系统</title>
    <link rel="stylesheet" href="../css/common.css">
    <style>
        .exams-header {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
        }

        .exams-title {
            font-size: 24px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .exams-subtitle {
            color: #666;
            font-size: 14px;
        }

        .exams-tabs {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            margin-bottom: 20px;
            overflow: hidden;
        }

        .tabs-nav {
            display: flex;
            border-bottom: 1px solid var(--border-color);
        }

        .tab-btn {
            flex: 1;
            padding: 16px 20px;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 14px;
            font-weight: 500;
            color: #666;
            transition: all 0.3s ease;
            border-bottom: 3px solid transparent;
        }

        .tab-btn.active {
            color: var(--primary-color);
            border-bottom-color: var(--primary-color);
            background: rgba(46, 134, 171, 0.05);
        }

        .tab-content {
            display: none;
            padding: 20px;
        }

        .tab-content.active {
            display: block;
        }

        .exams-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
        }

        .exam-card {
            background: white;
            border-radius: 8px;
            box-shadow: var(--shadow);
            overflow: hidden;
            transition: transform 0.3s ease;
        }

        .exam-card:hover {
            transform: translateY(-2px);
        }

        .exam-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
        }

        .exam-title {
            font-size: 18px;
            font-weight: bold;
            color: var(--neutral-dark);
            margin-bottom: 8px;
        }

        .exam-meta {
            font-size: 14px;
            color: #666;
            margin-bottom: 4px;
        }

        .exam-status {
            display: inline-block;
            padding: 4px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
            margin-top: 8px;
        }

        .exam-status.available {
            background: rgba(76, 175, 80, 0.1);
            color: var(--success-color);
        }

        .exam-status.completed {
            background: rgba(33, 150, 243, 0.1);
            color: #2196F3;
        }

        .exam-status.expired {
            background: rgba(158, 158, 158, 0.1);
            color: #9E9E9E;
        }

        .exam-body {
            padding: 20px;
        }

        .exam-info {
            display: flex;
            justify-content: space-between;
            margin-bottom: 16px;
            font-size: 14px;
            color: #666;
        }

        .exam-actions {
            display: flex;
            gap: 10px;
        }

        .btn-exam {
            flex: 1;
            padding: 10px 16px;
            border: none;
            border-radius: 6px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .btn-start {
            background: var(--success-color);
            color: white;
        }

        .btn-start:hover {
            background: #45a049;
        }

        .btn-view {
            background: var(--primary-color);
            color: white;
        }

        .btn-view:hover {
            background: #1e5f7a;
        }

        .btn-disabled {
            background: #ccc;
            color: #666;
            cursor: not-allowed;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #666;
        }

        .empty-state i {
            font-size: 64px;
            margin-bottom: 20px;
            color: #ccc;
        }

        .timer {
            position: fixed;
            top: 20px;
            right: 20px;
            background: var(--error-color);
            color: white;
            padding: 10px 20px;
            border-radius: 6px;
            font-weight: bold;
            z-index: 1000;
            display: none;
        }

        .exam-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.8);
            z-index: 2000;
            display: none;
            align-items: center;
            justify-content: center;
        }

        .exam-modal.show {
            display: flex;
        }

        .exam-modal-content {
            background: white;
            border-radius: 8px;
            width: 90%;
            max-width: 800px;
            max-height: 90vh;
            overflow-y: auto;
        }

        .exam-modal-header {
            padding: 20px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .exam-modal-title {
            font-size: 18px;
            font-weight: bold;
            margin: 0;
        }

        .exam-modal-close {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }

        .exam-modal-body {
            padding: 20px;
        }

        .question-card {
            background: #f8f9fa;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
        }

        .question-number {
            font-size: 14px;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 8px;
        }

        .question-content {
            font-size: 16px;
            line-height: 1.6;
            margin-bottom: 16px;
            color: var(--neutral-dark);
        }

        .question-options {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .question-options li {
            margin-bottom: 8px;
        }

        .option-label {
            display: flex;
            align-items: center;
            cursor: pointer;
            padding: 8px;
            border-radius: 4px;
            transition: background 0.3s ease;
        }

        .option-label:hover {
            background: rgba(46, 134, 171, 0.1);
        }

        .option-label input[type="radio"] {
            margin-right: 10px;
        }

        .exam-modal-footer {
            padding: 20px;
            border-top: 1px solid var(--border-color);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .progress-info {
            font-size: 14px;
            color: #666;
        }

        .modal-actions {
            display: flex;
            gap: 10px;
        }

        @media (max-width: 768px) {
            .exams-grid {
                grid-template-columns: 1fr;
            }
            
            .tabs-nav {
                flex-direction: column;
            }
            
            .exam-modal-content {
                width: 95%;
                margin: 10px;
            }
        }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <nav class="navbar">
        <div class="container-fluid">
            <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <a href="index.html" class="navbar-brand">
                    📚 局域网视频学习系统
                </a>
                <div style="display: flex; align-items: center; gap: 20px;">
                    <a href="index.html" style="color: var(--neutral-dark); text-decoration: none;">
                        🏠 首页
                    </a>
                    <a href="favorites.html" style="color: var(--neutral-dark); text-decoration: none;">
                        ❤️ 我的收藏
                    </a>
                    <a href="playlists.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📋 播放列表
                    </a>
                    <a href="exams.html" style="color: var(--neutral-dark); text-decoration: none;">
                        📝 考试中心
                    </a>
                    <a href="profile.html" style="color: var(--neutral-dark); text-decoration: none;">
                        👤 个人资料
                    </a>
                    <span style="color: var(--neutral-dark);">
                        <span data-user-name>学生</span>
                    </span>
                    <button onclick="logout()" class="logout-btn">
                        退出登录
                    </button>
                </div>
            </div>
        </div>
    </nav>

    <!-- 主内容区 -->
    <div class="content-wrapper">
        <!-- 页面标题 -->
        <div class="exams-header">
            <h1 class="exams-title">考试中心</h1>
            <p class="exams-subtitle">参加在线考试，检验学习成果</p>
        </div>

        <!-- 考试标签页 -->
        <div class="exams-tabs">
            <div class="tabs-nav">
                <button class="tab-btn active" onclick="switchTab('available')">可参加考试</button>
                <button class="tab-btn" onclick="switchTab('completed')">已完成考试</button>
                <button class="tab-btn" onclick="switchTab('expired')">已过期考试</button>
            </div>

            <!-- 可参加考试 -->
            <div class="tab-content active" id="availableTab">
                <div class="exams-grid" id="availableExams">
                    <div class="loading">
                        <div class="loading"></div>
                        加载中...
                    </div>
                </div>
            </div>

            <!-- 已完成考试 -->
            <div class="tab-content" id="completedTab">
                <div class="exams-grid" id="completedExams">
                    <div class="loading">
                        <div class="loading"></div>
                        加载中...
                    </div>
                </div>
            </div>

            <!-- 已过期考试 -->
            <div class="tab-content" id="expiredTab">
                <div class="exams-grid" id="expiredExams">
                    <div class="loading">
                        <div class="loading"></div>
                        加载中...
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 考试计时器 -->
    <div class="timer" id="examTimer">
        剩余时间: <span id="timeLeft">00:00</span>
    </div>

    <!-- 考试模态框 -->
    <div class="exam-modal" id="examModal">
        <div class="exam-modal-content">
            <div class="exam-modal-header">
                <h3 class="exam-modal-title" id="examModalTitle">考试</h3>
                <button class="exam-modal-close" onclick="closeExamModal()">&times;</button>
            </div>
            <div class="exam-modal-body" id="examModalBody">
                <!-- 考试内容将在这里生成 -->
            </div>
            <div class="exam-modal-footer">
                <div class="progress-info" id="progressInfo">
                    第 1 题，共 10 题
                </div>
                <div class="modal-actions">
                    <button class="btn btn-secondary" onclick="closeExamModal()">退出考试</button>
                    <button class="btn btn-primary" onclick="submitExam()">提交答案</button>
                </div>
            </div>
        </div>
    </div>

    <script src="../js/common.js"></script>
    <script>
        let currentExams = [];
        let currentExam = null;
        let currentQuestionIndex = 0;
        let examAnswers = {};
        let examTimer = null;
        let timeLeft = 0;

        // 页面初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 检查权限
            if (!UserManager.hasPermission(2)) {
                Message.error('权限不足');
                setTimeout(() => {
                    window.location.href = '../login.html';
                }, 2000);
                return;
            }

            // 加载考试数据
            loadExams();
        });

        // 切换标签页
        function switchTab(tabName) {
            // 更新标签按钮状态
            document.querySelectorAll('.tab-btn').forEach(btn => btn.classList.remove('active'));
            event.target.classList.add('active');

            // 更新标签内容
            document.querySelectorAll('.tab-content').forEach(content => content.classList.remove('active'));
            document.getElementById(tabName + 'Tab').classList.add('active');

            // 加载对应数据
            loadTabData(tabName);
        }

        // 加载考试数据
        async function loadExams() {
            try {
                const response = await API.get('/exam/student/list');
                if (response.success) {
                    currentExams = response.exams;
                    loadTabData('available');
                } else {
                    Message.error('加载考试数据失败');
                }
            } catch (error) {
                console.error('加载考试失败:', error);
                Message.error('加载考试数据失败');
            }
        }

        // 加载标签页数据
        function loadTabData(tabName) {
            const container = document.getElementById(tabName + 'Exams');
            
            let exams = [];
            switch (tabName) {
                case 'available':
                    // 直接使用后端返回的studentStatus判断
                    // studentStatus !== 2 且 exam.status === 1 才是可参加
                    exams = currentExams.filter(exam => exam.studentStatus !== 2 && exam.status === 1);
                    break;
                case 'completed':
                    // 直接使用后端返回的studentStatus判断
                    // studentStatus === 2 才是已完成
                    exams = currentExams.filter(exam => exam.studentStatus === 2);
                    break;
                case 'expired':
                    exams = currentExams.filter(exam => exam.status === 2); // 已结束
                    break;
            }

            if (exams.length === 0) {
                container.innerHTML = `
                    <div class="empty-state" style="grid-column: 1 / -1;">
                        <i>📝</i>
                        <p>暂无${getTabTitle(tabName)}</p>
                    </div>
                `;
                return;
            }

            container.innerHTML = exams.map(exam => `
                <div class="exam-card">
                    <div class="exam-header">
                        <h3 class="exam-title">${exam.title}</h3>
                        <div class="exam-meta">出题老师: ${exam.teacherName || '未知'}</div>
                        <div class="exam-meta">题目数量: ${exam.totalQuestions || 0} 题</div>
                        <div class="exam-meta">总分: ${exam.totalScore || 0} 分</div>
                        <div class="exam-meta">时间限制: ${exam.timeLimit || 0} 分钟</div>
                        <span class="exam-status ${getExamStatusClass(exam, tabName)}">
                            ${getExamStatusText(exam, tabName)}
                        </span>
                    </div>
                    <div class="exam-body">
                        <div class="exam-info">
                            <span>创建时间: ${Utils.formatTime(exam.createdTime)}</span>
                            ${exam.completed ? `<span>完成时间: ${Utils.formatTime(exam.completedTime)}</span>` : ''}
                        </div>
                        <div class="exam-actions">
                            ${getExamActions(exam, tabName)}
                        </div>
                    </div>
                </div>
            `).join('');
        }

        // 获取标签页标题
        function getTabTitle(tabName) {
            switch (tabName) {
                case 'available': return '可参加考试';
                case 'completed': return '已完成考试';
                case 'expired': return '已过期考试';
                default: return '考试';
            }
        }

        // 获取考试状态样式类
        function getExamStatusClass(exam, tabName) {
            switch (tabName) {
                case 'available': return 'available';
                case 'completed': return 'completed';
                case 'expired': return 'expired';
                default: return '';
            }
        }

        // 获取考试状态文本
        function getExamStatusText(exam, tabName) {
            switch (tabName) {
                case 'available': return '可参加';
                case 'completed': return '已完成';
                case 'expired': return '已过期';
                default: return '未知';
            }
        }

        // 获取考试操作按钮
        function getExamActions(exam, tabName) {
            switch (tabName) {
                case 'available':
                    return `<button class="btn-exam btn-start" onclick="startExam(${exam.id})">开始考试</button>`;
                case 'completed':
                    return `<button class="btn-exam btn-view" onclick="viewExamResult(${exam.id})">查看结果</button>`;
                case 'expired':
                    return `<button class="btn-exam btn-disabled" disabled>已过期</button>`;
                default:
                    return '';
            }
        }

        // 开始考试
        async function startExam(examId) {
            try {
                const response = await API.post(`/exam/start/${examId}`);
                if (response.success) {
                    // 保存考试数据到sessionStorage
                    sessionStorage.setItem('currentExam', JSON.stringify({
                        exam: response.exam,
                        questions: response.questions
                    }));
                    
                    // 跳转到新的答题页面
                    window.location.href = 'exam-taking-new.html';
                } else {
                    Message.error(response.message || '开始考试失败');
                }
            } catch (error) {
                console.error('开始考试失败:', error);
                Message.error('开始考试失败');
            }
        }

        // 显示考试模态框
        function showExamModal() {
            document.getElementById('examModal').classList.add('show');
            document.getElementById('examModalTitle').textContent = currentExam.title;
            document.body.style.overflow = 'hidden';
        }

        // 关闭考试模态框
        function closeExamModal() {
            if (examTimer) {
                clearInterval(examTimer);
                examTimer = null;
            }
            document.getElementById('examModal').classList.remove('show');
            document.getElementById('examTimer').style.display = 'none';
            document.body.style.overflow = '';
        }

        // 加载考试题目
        async function loadExamQuestions() {
            try {
                const response = await API.get(`/exam/${currentExam.id}/questions`);
                if (response.success) {
                    const questions = response.questions;
                    renderQuestion(questions[currentQuestionIndex], currentQuestionIndex + 1, questions.length);
                } else {
                    Message.error('加载题目失败');
                }
            } catch (error) {
                console.error('加载题目失败:', error);
                Message.error('加载题目失败');
            }
        }

        // 渲染题目
        function renderQuestion(question, questionNum, totalQuestions) {
            const container = document.getElementById('examModalBody');
            const progressInfo = document.getElementById('progressInfo');
            
            progressInfo.textContent = `第 ${questionNum} 题，共 ${totalQuestions} 题`;
            
            container.innerHTML = `
                <div class="question-card">
                    <div class="question-number">第 ${questionNum} 题</div>
                    <div class="question-content">${question.content}</div>
                    <ul class="question-options">
                        <li>
                            <label class="option-label">
                                <input type="radio" name="question_${question.id}" value="A" 
                                       ${examAnswers[question.id] === 'A' ? 'checked' : ''}>
                                A. ${question.optionA}
                            </label>
                        </li>
                        <li>
                            <label class="option-label">
                                <input type="radio" name="question_${question.id}" value="B" 
                                       ${examAnswers[question.id] === 'B' ? 'checked' : ''}>
                                B. ${question.optionB}
                            </label>
                        </li>
                        <li>
                            <label class="option-label">
                                <input type="radio" name="question_${question.id}" value="C" 
                                       ${examAnswers[question.id] === 'C' ? 'checked' : ''}>
                                C. ${question.optionC}
                            </label>
                        </li>
                        <li>
                            <label class="option-label">
                                <input type="radio" name="question_${question.id}" value="D" 
                                       ${examAnswers[question.id] === 'D' ? 'checked' : ''}>
                                D. ${question.optionD}
                            </label>
                        </li>
                    </ul>
                </div>
            `;
            
            // 绑定选项选择事件
            container.querySelectorAll('input[type="radio"]').forEach(radio => {
                radio.addEventListener('change', function() {
                    examAnswers[question.id] = this.value;
                });
            });
        }

        // 开始计时器
        function startTimer() {
            document.getElementById('examTimer').style.display = 'block';
            updateTimerDisplay();
            
            examTimer = setInterval(() => {
                timeLeft--;
                updateTimerDisplay();
                
                if (timeLeft <= 0) {
                    clearInterval(examTimer);
                    Message.warning('考试时间到，自动提交答案');
                    submitExam();
                }
            }, 1000);
        }

        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            document.getElementById('timeLeft').textContent = 
                `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        // 提交考试
        async function submitExam() {
            try {
                // 计算分数
                const score = calculateScore();
                
                const response = await API.post(`/exam/${currentExam.id}/complete`, {
                    score: score,
                    answers: examAnswers
                });
                
                if (response.success) {
                    closeExamModal();
                    Message.success(`考试完成！您的得分：${score} 分`);
                    loadExams(); // 重新加载考试列表
                } else {
                    Message.error(response.message || '提交考试失败');
                }
            } catch (error) {
                console.error('提交考试失败:', error);
                Message.error('提交考试失败');
            }
        }

        // 计算分数
        function calculateScore() {
            // 这里需要根据正确答案来计算分数
            // 暂时返回随机分数作为示例
            return Math.floor(Math.random() * 100);
        }

        // 查看考试结果
        function viewExamResult(examId) {
            // 跳转到考试结果页面
            window.location.href = `exam-result.html?examId=${examId}`;
        }

        // 退出登录
        async function logout() {
            try {
                await API.post('/user/logout');
                sessionStorage.removeItem('user');
                window.location.href = '../login.html';
            } catch (error) {
                console.error('退出登录失败:', error);
                Message.error('退出登录失败');
            }
        }
    </script>
</body>
</html>
